package com.example.gulimall.product.exception;

import com.example.common.utils.R;
import exception.BizCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.example.gulimall.product.controller")
public class GulimallProductControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException ex){

        log.error("数据校验出现异常：{0}，异常类型是：{1}",ex.getMessage(),ex.getClass());
        //获取所有异常
        BindingResult bindResult=ex.getBindingResult();
        Map<String,String> errorMap=new HashMap<>();
        //箭头函数遍历错误异常;
        bindResult.getFieldErrors().forEach((FieldError)->{
            errorMap.put(FieldError.getField(),FieldError.getDefaultMessage());
        });
       return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",errorMap);

    }
    @ExceptionHandler(value = Throwable.class)
    public  R handleException(Throwable throwable){
        log.error("错误：",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
